package com.qpl.depression.cms.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qpl.depression.cms.common.ServerResponse;
import com.qpl.depression.cms.entity.Question;
import com.qpl.depression.cms.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    /**
     * 问答详情页面
     *
     * @return
     */
    @GetMapping("question/page")
    public String questionPage() {
        return "questionList";
    }

    /**
     * 问答详情数据
     *
     * @return
     */
    @GetMapping("question/data")
    @ResponseBody
    public ServerResponse questionData(String name) {
        List<Question> questions = questionService.list(Wrappers.<Question>lambdaQuery()
                .like(StringUtils.isNotBlank(name), Question::getQuestion, name)
        );
        return ServerResponse.createBySuccess("查询成功", questions);
    }

    /**
     * 问答详情编辑
     *
     * @return
     */
    @GetMapping("question/edit")
    public String questionEdit(@RequestParam("id") Long id, Model model) {
        Question question = questionService.getById(id);
        model.addAttribute("question", question);
        return "questionEditPage";
    }

    /**
     * 问答详情删除
     *
     * @return
     */
    @GetMapping("question/del")
    @ResponseBody
    public ServerResponse del(Long id) {
        return questionService.removeById(id) ? ServerResponse.createBySuccessMessage("成功") : ServerResponse.createByErrorMessage("失败");
    }

    /**
     * 问答详情更新
     *
     * @return
     */
    @PostMapping("question/update")
    @ResponseBody
    public ServerResponse questionUpdate(Question question) {
        question.setStatus(1);
        return questionService.updateById(question) ? ServerResponse.createBySuccessMessage("成功") : ServerResponse.createByErrorMessage("失败");
    }
}
